package com.starsea.book.ui.newpage.utils

import android.os.Build
import android.text.TextUtils
import java.util.Locale

/**
 * Function:手机ROM工具类
 * Description:
 */
object RomUtil {
  private const val KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name"
  private const val KEY_EMUI_VERSION_NAME = "ro.build.version.emui"
  val isMIUI: Boolean
    /**
     * 判断是否为MIUI
     *
     * @return
     */
    get() {
      val property = getSystemProperty(KEY_MIUI_VERSION_NAME, "")
      return !TextUtils.isEmpty(property)
    }
  val mIUIVersion: String
    /**
     * 获取MUI版本
     *
     * @return
     */
    get() = if (isMIUI) getSystemProperty(KEY_MIUI_VERSION_NAME, "") else ""
  val mIUIVersionCode: Int
    /**
     * 获取MIUI版本-数字用于大小判断
     *
     * @return
     */
    get() {
      var code = -1
      var property = mIUIVersion
      try {
        property = property.trim { it <= ' ' }
          .uppercase(Locale.getDefault()).replace("V", "")
        code = property.toInt()
      } catch (e: Exception) {
        e.printStackTrace()
      }
      return code
    }
  val isEMUI: Boolean
    /**
     * 判断是否为EMUI
     *
     * @return
     */
    get() {
      val property = getSystemProperty(KEY_EMUI_VERSION_NAME, "")
      return !TextUtils.isEmpty(property)
    }
  val eMUIVersion: String
    /**
     * 获取EMUI的版本
     *
     * @return
     */
    get() = if (isEMUI) getSystemProperty(KEY_EMUI_VERSION_NAME, "") else ""
  val isFlyme: Boolean
    /**
     * 判断是否为Flyme
     *
     * @return
     */
    get() = Build.DISPLAY.lowercase(Locale.getDefault()).contains("flyme")
  val flymeVersion: String
    /**
     * 获取Flyme的版本
     *
     * @return
     */
    get() = if (isFlyme) Build.DISPLAY else ""
  val flymeVersionCode: Int
    /**
     * 获取Flyme版本号
     *
     * @return
     */
    get() {
      var code = 0
      val version = flymeVersion
      if (!TextUtils.isEmpty(version)) {
        code = if (version.lowercase(Locale.getDefault()).contains("os")) {
          Integer.valueOf(version.substring(9, 10))
        } else {
          Integer.valueOf(version.substring(6, 7))
        }
      }
      return code
    }

  /**
   * 通过反射获取系统属性
   *
   * @param key
   * @param defaultValue
   * @return
   */
  fun getSystemProperty(key: String?, defaultValue: String): String {
    try {
      val clz = Class.forName("android.os.SystemProperties")
      val get = clz.getMethod("get", String::class.java, String::class.java)
      return get.invoke(clz, key, defaultValue) as String
    } catch (e: Exception) {
      e.printStackTrace()
    }
    return defaultValue
  }
}
